"""
This training script can be run both on a single gpu in debug mode,
and also in a larger training run with distributed data parallel (ddp).

To run on a single GPU, example:
$ python train_gpt.py --batch_size=32 --compile=False

To run with DDP on 4 gpus on 1 node, example:
$ torchrun --standalone --nproc_per_node=4 train_gpt.py

To run with DDP on 4 gpus across 2 nodes, example:
- Run on the first (master) node with example IP 123.456.123.456:
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train_gpt.py
- Run on the worker node:
$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train_gpt.py
(If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1)

3) ddp
https://zhuanlan.zhihu.com/p/178402798

目前在我的macbook m1 上运行的命令如下，使用mps加速训练：
python train_gpt.py config/train_shakespeare_char.py --device=mps --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0
"""
import os
import time
from contextlib import nullcontext

import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed import init_process_group, destroy_process_group

from model import GPTConfig, GPT
from data.data_utils import get_batch, OUTPUT_PATH
from train_utils import configure_optimizers, get_lr

# -----------------------------------------------------------------------------
# default config values designed to train a gpt2 (124M) on OpenWebText

# general
data_name = ''
model_name = 'gpt'
# I/O
eval_interval = 2000
log_interval = 1
eval_iters = 200
eval_only = False  # if True, script exits right after the first eval
always_save_checkpoint = True  # if True, always save a checkpoint after each eval
init_from = 'scratch'  # 'scratch' or 'resume' or 'gpt2*'
# wandb logging
wandb_log = False  # disabled by default
wandb_project = 'owt'
wandb_run_name = 'gpt2'  # 'run' + str(time.time())
# data
# dataset = 'openwebtext'
gradient_accumulation_steps = 5 * 8  # used to simulate larger batch sizes
batch_size = 12  # if gradient_accumulation_steps > 1, this is the micro-batch size
block_size = 1024
meta_vocab_size = 50304  # defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)
# model
n_layer = 12
n_head = 12
n_embd = 768
dropout = 0.0  # for pretraining 0 is good, for fine-tuning try 0.1+
bias = False  # do we use bias inside LayerNorm and Linear layers?
# adamw optimizer
learning_rate = 6e-4  # default learning rate
max_iters = 3000  # total number of training iterations
weight_decay = 1e-1
beta1 = 0.9
beta2 = 0.95
grad_clip = 1.0  # clip gradients at this value, or disable if == 0.0
# learning rate decay settings
lr_decay_method = 'cosine_with_warmup'  # set to None if not decay the learning rate
warmup_iters = 2000  # how many steps to warm up for
lr_decay_iters = 600000  # should be ~= max_iters per Chinchilla
min_lr = 6e-5  # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
max_lr = 6e-4
# DDP settings
backend = 'nccl'  # 'nccl', 'gloo', etc.
# system
device = 'mps'  # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on Mac
dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16'  # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
compile = True  # use PyTorch 2.0 to compile the model to be faster
# -----------------------------------------------------------------------------
config_keys = [k for k, v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
exec(open('../configurator.py').read())  # overrides from command line or config file
config = {k: globals()[k] for k in config_keys}  # will be useful for logging
# -----------------------------------------------------------------------------

# various inits, derived attributes, I/O setup
ddp = int(os.environ.get('RANK', -1)) != -1  # is this a ddp run?
if ddp:
    # 举个例子：我有两台机子，每台8张显卡(GPU)，那就是2x8 = 16个进程，并行数是16，DDP会同时启动16个进程。
    # 在默认(最佳)状态下，一张显卡对应一个进程。
    init_process_group(backend=backend)  # 初始化DDP，使用默认backend(nccl)就行。如果是CPU模型运行，需要选择其他后端。
    ddp_rank = int(os.environ['RANK'])  # 表现当前进程的序号，用于进程间通讯。例如对于16的world size来说，就是0,1,2,…,15。
    ddp_local_rank = int(os.environ['LOCAL_RANK'])  # 这是每台机子上的进程的序号。机器一上有0,1,2,3,4,5,6,7，机器二上也有0,1,2,3,4,5,6,7
    ddp_world_size = int(os.environ['WORLD_SIZE'])  # 表示总进程数量，简单来讲，就是2x8=16。
    device = f'cuda:{ddp_local_rank}'  # 当前机器的当前进程对应的device(GPU)。比如，代表机器一的第4张显卡
    torch.cuda.set_device(device)  # 根据local_rank来设定当前使用哪块GPU
    master_process = ddp_rank == 0  # this process will do logging, checkpointing etc. rank=0的进程就是master进程。
    seed_offset = ddp_rank  # each process gets a different seed
    # world_size number of processes will be training simultaneously, so we can scale
    # down the desired gradient accumulation iterations per process proportionally
    assert gradient_accumulation_steps % ddp_world_size == 0
    gradient_accumulation_steps //= ddp_world_size  # 使得每个ddp进程使用batch_size / 进程数 的样本，则每个iter仍然使用batch_size个样本计算梯度更新参数
else:
    # if not ddp, we are running on a single gpu, and one process
    master_process = True
    seed_offset = 0
    ddp_world_size = 1
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
print(f"tokens per iteration will be: {tokens_per_iter:,}")

if master_process:
    os.makedirs(OUTPUT_PATH, exist_ok=True)
torch.manual_seed(1337 + seed_offset)
torch.backends.cuda.matmul.allow_tf32 = True  # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True  # allow tf32 on cudnn
device_type = 'cuda' if 'cuda' in device else 'cpu'  # for later use in torch.autocast
# note: float16 data type will automatically use a GradScaler
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)

# # poor man's data loader
# data_dir = os.path.join('../data', dataset)


# init these up here, can override if init_from='resume' (i.e. from a checkpoint)
cur_iter = 0
best_val_loss = 1e9

# model init
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
                  bias=bias, vocab_size=meta_vocab_size, dropout=dropout)  # start with model_args from command line

if init_from == 'scratch':
    # init a new model from scratch
    print("Initializing a new model from scratch")
    gptconf = GPTConfig(**model_args)
    model = GPT(gptconf)
elif init_from == 'resume':
    print(f"Resuming training from {OUTPUT_PATH}")
    # resume training from a checkpoint.
    ckpt_path = os.path.join(OUTPUT_PATH, f'{model_name}_ckpt.pt')
    checkpoint = torch.load(ckpt_path, map_location=device)
    checkpoint_model_args = checkpoint['model_args']
    # force these config attributes to be equal otherwise we can't even resume training
    # the rest of the attributes (e.g. dropout) can stay as desired from command line
    for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
        model_args[k] = checkpoint_model_args[k]
    # create the model
    gptconf = GPTConfig(**model_args)
    model = GPT(gptconf)
    state_dict = checkpoint['model']
    # fix the keys of the state dictionary :(
    # honestly no idea how checkpoints sometimes get this prefix, have to debug more
    unwanted_prefix = '_orig_mod.'
    for k, v in list(state_dict.items()):
        if k.startswith(unwanted_prefix):
            state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
    model.load_state_dict(state_dict)
    cur_iter = checkpoint['iter_num']
    best_val_loss = checkpoint['best_val_loss']
elif init_from.startswith('gpt2'):
    print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
    # initialize from OpenAI GPT-2 weights
    override_args = dict(dropout=dropout)
    model = GPT.from_pretrained(init_from, override_args)
    # read off the created config params, so we can store them into checkpoint correctly
    for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
        model_args[k] = getattr(model.config, k)
else:
    raise NotImplementedError

# crop down the model block size if desired, using model surgery
if block_size < model.config.block_size:
    model.crop_block_size(block_size)
    model_args['block_size'] = block_size  # so that the checkpoint will have the right value

# 定义并把模型放置到单独的GPU上，需要在调用`model=DDP(model)`前进行
model.to(device)

# initialize a GradScaler. If enabled=False scaler is a no-op
scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))

# optimizer
optimizer = configure_optimizers(model, weight_decay, learning_rate, (beta1, beta2), device_type)
if init_from == 'resume':
    optimizer.load_state_dict(checkpoint['optimizer'])
checkpoint = None  # free up memory

# compile the model
if compile:
    print("compiling the model... (takes a ~minute)")
    unoptimized_model = model
    model = torch.compile(model)  # requires PyTorch 2.0

# wrap model into DDP container
# DDP的使用非常简单，因为它不需要修改你网络的配置，只需要将模型使用DDP包装起来就好
if ddp:
    model = DDP(model, device_ids=[ddp_local_rank])

# logging
if wandb_log and master_process:
    import wandb

    wandb.init(project=wandb_project, name=wandb_run_name, config=config)

# training loop
X, Y = get_batch(block_size, batch_size, split='train', data_name=data_name,
                 device=device)  # fetch the very first batch
t0 = time.time()
local_iter_num = 0  # number of iterations in the lifetime of this process
# save模型的时候，和DP模式一样，有一个需要注意的点：保存的是model.module而不是model。因为model其实是DDP model，参数是被`model=DDP(model)`包起来的。
raw_model = model.module if ddp else model  # unwrap DDP container if needed
running_mfu = -1.0


@torch.no_grad()
def estimate_loss():
    # helps estimate an arbitrarily accurate loss over either split using many batches
    out = {}
    model.eval()
    for split in ['train', 'val']:
        _losses = torch.zeros(eval_iters)
        for k in range(eval_iters):
            x, y = get_batch(block_size, batch_size, split, data_name, device=device)
            with ctx:
                _, _loss = model(x, y)
            _losses[k] = _loss.item()
        out[split] = _losses.mean()
    model.train()
    return out


while True:

    # determine and set the learning rate for this iteration
    lr = get_lr(lr_decay_method, cur_iter, warmup_iters, lr_decay_iters, min_lr, max_lr, learning_rate)
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

    # evaluate the loss on train/val sets and write checkpoints
    if cur_iter % eval_interval == 0 and master_process:  # 只需要在进程0上保存一次模型就行了，避免多次保存重复的东西。
        losses = estimate_loss()
        print(f"step {cur_iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
        if wandb_log:
            wandb.log({
                "iter": cur_iter,
                "train/loss": losses['train'],
                "val/loss": losses['val'],
                "lr": lr,
                "mfu": running_mfu * 100,  # convert to percentage
            })
        if losses['val'] < best_val_loss or always_save_checkpoint:
            best_val_loss = losses['val']
            if cur_iter > 0:
                checkpoint = {
                    'model': raw_model.state_dict(),
                    'optimizer': optimizer.state_dict(),
                    'model_args': model_args,
                    'iter_num': cur_iter,
                    'best_val_loss': best_val_loss,
                    'config': config,
                }
                print(f"saving checkpoint to {OUTPUT_PATH}")
                torch.save(checkpoint, os.path.join(OUTPUT_PATH, f'{model_name}_ckpt.pt'))
    if cur_iter == 0 and eval_only:
        break

    # forward backward update, with optional gradient accumulation to simulate larger batch size
    # and using the GradScaler if data type is float16
    for micro_step in range(gradient_accumulation_steps):
        if ddp:
            # in DDP training we only need to sync gradients at the last micro step.
            # the official way to do this is with model.no_sync() context manager, but
            # I really dislike that this bloats the code and forces us to repeat code
            # looking at the source of that context manager, it just toggles this variable
            # 当require_backward_grad_sync为True时，DDP会在每次反向传播时同步所有进程的梯度。这是默认行为，确保所有模型副本的参数在每次训练步骤后保持一致。
            # 当require_backward_grad_sync为False时，DDP不会在反向传播时同步梯度。这在某些情况下非常有用。
            # 在梯度累积（gradient accumulation）过程中，我们在多个小批次（micro_step）上累积梯度，然后在最后一个micro_step上设置
            # require_backward_grad_sync为True，以减少通信开销。这是因为只有在最后一个micro_step上我们需要反向传播更新参数
            model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
        with ctx:
            logits, loss = model(X, Y)
            loss = loss / gradient_accumulation_steps  # scale the loss to account for gradient accumulation
        # immediately async prefetch next batch while model is doing the forward pass on the GPU
        X, Y = get_batch(block_size, batch_size, split='train', data_name=data_name, device=device)
        # backward pass, with gradient scaling if training in fp16
        # backward累加参数的梯度
        scaler.scale(loss).backward()
    # clip the gradient
    if grad_clip != 0.0:
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
    # step the optimizer and scaler if training in fp16
    # step the optimizer可以更新参数
    scaler.step(optimizer)
    scaler.update()
    # flush the gradients as soon as we can, no need for this memory anymore
    optimizer.zero_grad(set_to_none=True)

    # timing and logging
    t1 = time.time()
    dt = t1 - t0
    t0 = t1
    if cur_iter % log_interval == 0 and master_process:
        # get loss as float. note: this is a CPU-GPU sync point
        # scale up to undo the division above, approximating the true total loss (exact would have been a sum)
        lossf = loss.item() * gradient_accumulation_steps
        print(f"iter {cur_iter}: loss {lossf:.4f}, time {dt * 1000:.2f}ms")
    cur_iter += 1
    local_iter_num += 1

    # termination conditions
    if cur_iter > max_iters:
        break

if ddp:
    destroy_process_group()
